<template>
  <div class="course-container">
    <el-card class="course-card">
      <template #header>
        <div class="card-header">
          <span>课程管理</span>
          <el-button type="primary" size="small" @click="handleAdd">新增课程</el-button>
        </div>
      </template>

      <el-table :data="programList" border style="width: 100%">
        <el-table-column label="序号" width="80">
                    <template #default="scope">
                        {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
                    </template>
        </el-table-column>
        <el-table-column prop="name" label="课程名称" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="category_name" label="所属类别名称" width="120" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        class="pagination"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="fetchProgramData"
        @current-change="fetchProgramData"
      />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="form" label-width="80px">
        <el-form-item label="课程名称">
          <el-input v-model="form.name" placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="所属类别">
          <el-select v-model="form.category_id" placeholder="请选择类别">
            <el-option
              v-for="category in categoryList"
              :key="category.category_id"
              :label="category.name"
              :value="category.category_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入描述" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import requestUtil from '@/util/request.js'

// 表格数据
const programList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 类别列表（用于下拉选择）
const categoryList = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const form = ref({
  program_id: null,
  name: '',
  description: '',
  category_id: null
})

// 获取课程数据
const fetchProgramData = async () => {
  try {
    const res = await requestUtil.get('/program/msg', {
        page: currentPage.value,
        page_size: pageSize.value
    })
    // 添加 category_name 字段
    const programWithCategoryName = res.data.data.map(program => ({
      ...program,
      category_name: getCategoryNameById(program.category_id)
    }))
    console.log('请求页码:', currentPage.value)
    console.log('每页数量:', pageSize.value)
    programList.value = programWithCategoryName
    total.value = res.data.total
  } catch (error) {
    console.error('获取课程数据失败:', error)
  }
}

// 获取所有类别（用于下拉框）
const fetchCategoryList = async () => {
  try {
    const res = await requestUtil.get('/category/msg')
    categoryList.value = res.data.data || []
  } catch (error) {
    console.error('获取类别列表失败:', error)
  }
}
// 根据 category_id 获取类别名称
const getCategoryNameById = (categoryId) => {
  const category = categoryList.value.find(c => c.category_id === categoryId)
  return category ? category.name : '未知类别'
}

// 新增课程
const handleAdd = () => {
  dialogTitle.value = '新增课程'
  form.value = {
    program_id: null,
    name: '',
    description: '',
    category_id: null
  }
  dialogVisible.value = true
}

// 编辑课程
const handleEdit = (row) => {
  dialogTitle.value = '编辑课程'
  form.value = { ...row }
  dialogVisible.value = true
}

// 删除课程
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除【${row.name}】课程吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await requestUtil.del(`/program/delete/${row.program_id}`)
      ElMessage.success('删除成功')
      await fetchProgramData()
    } catch (error) {
      console.error('删除失败:', error)
    }
  }).catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 从本地存储获取用户ID
    const userId = localStorage.getItem('user_id')

    if (!userId) {
      ElMessage.error('用户未登录或会话已过期，请重新登录')
      return
    }
    if (form.value.program_id) {
      // 编辑
      await requestUtil.put(`/program/update/${form.value.program_id}`, {
        name: form.value.name,
        description: form.value.description,
        category_id: form.value.category_id
      })
      ElMessage.success('更新成功')
    } else {
      // 新增
      await requestUtil.post('/program/add', {
        name: form.value.name,
        description: form.value.description,
        category_id: form.value.category_id,
        create_by_id:userId
      })
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    await fetchProgramData()
  } catch (error) {
    console.error('操作失败:', error)
  }
}

onMounted(() => {
  fetchCategoryList()
  fetchProgramData()
})
</script>

<style lang="scss" scoped>
.course-container {
  padding: 20px 0;

  .course-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 10px;
    }
  }

  .pagination {
    margin-top: 20px;
    justify-content: flex-end;
  }
}
</style>
